package com.me.study.javaBasic.dataType;

import org.junit.Assert;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class TestSimpleDateFormat {

	/**
	 * 日期格式解析：GMT时区（一般时区）
	 */
	@Test
	public void testGMT() throws ParseException {
		// 获取当前系统的毫秒数
		long min = System.currentTimeMillis();
		// 通过毫秒数构建系统时间
		Date d1 = new Date(min);
		System.out.println("指定毫米数的时间：" + d1.toLocaleString());

		// TODO 格式化模板里的 `'GMT'XXX` 和 `z` 都表示 时区，格式化之后的文本为 `GMT+08:00`
		String s = "Mon Feb 13 08:20:23 GMT+08:00 2012";
		SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.CHINA);
		Date date = sf.parse(s);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'GMT'XXX");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		String result = sdf.format(date);
		Assert.assertEquals("解析 GMT时区", "2012-02-13 08:20:23 GMT+08:00", result);
	}

	/**
	 * 日期格式解析：CST时区（一般时区）
	 */
	@Test
	public void testCST() throws ParseException {
		String str = "Mon Dec 31 09:29:55 CST 2012";
		// SimpleDateFormat sf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		SimpleDateFormat sf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy", Locale.US);
		Date date = sf.parse(str);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String result = sdf.format(date);
		Assert.assertEquals("解析 CST时区", "2012-12-31 09:29:55", result);
	}

	/**
	 * 日期格式解析：RFC822时区（一般时区）
	 */
	@Test
	public void testRFC822() throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String str = "2007-05-01T15:43:26.3452+08:00";
		str = str.replaceAll("([\\+\\-]\\d\\d):(\\d\\d)","$1$2");
		SimpleDateFormat sf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
		Date date = sf.parse(str);
		String result = sdf.format(date);
		Assert.assertEquals("解析 RFC822时区", "2007-05-01 15:43:29", result);

		str = "2007-05-01T15:43:26.3452Z";
		sf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
		date = sf.parse(str);
		result = sdf.format(date);
		Assert.assertEquals("解析 RFC822时区，已 `Z`结尾", "2007-05-01 15:43:29", result);

		str = "Mon, 31 Dec 2012 15:43:26+08:00";
		str = str.replaceAll("([\\+\\-]\\d\\d):(\\d\\d)","$1$2");
		sf = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ssZ", Locale.US);
		date = sf.parse(str);
		result = sdf.format(date);
		Assert.assertEquals("解析 RFC822时区，美国本地化", "2012-12-31 15:43:26", result);
	}

}
